<template>
    <div id="mainwindow" ref="mainWindow">
        <!-- <pui-window defaultWidth="100%" defaultHeight="100%" :title="diagram.value.label" id="windows" @changeWindow="reload()" @closeWindow="deleteWindow(index)" :class="{'focusStyle':focusid == index}" @click="focusWindow(index)" v-for="(diagram,index) in diagrams" :key="index" :rightItemList="windowRef.rightItemList">
            <p id="diagram" :class=diagram.value>
                <eye-diagram ref="EyeDiagramRef" v-if="diagram.value.label == '眼图'"></eye-diagram>
                <bit-error ref="BitErrorRef" v-if="diagram.value.label == '误码率'"></bit-error>
                <planis-phere ref="PlanisPhereRef" v-if="diagram.value.label == '星座图'"></planis-phere>
                <wave-form ref="WaveFormRef" v-if="diagram.value.label == '波形图'"></wave-form>
                <matrix-diagram ref="MatrixDiagramRef" v-if="diagram.value.label == '电场E'"></matrix-diagram>
            </p>
        </pui-window> -->
        <div class="preview-list">
            <div class="preview-item" v-for="(diagram,index) in diagrams" :key="index">
                <div class="title">{{ diagram.value.label }}</div>
                <div id="diagram" :class=diagram.value>
                    <eye-diagram ref="chartsRef" v-if="diagram.value.label == '眼图'"></eye-diagram>
                    <bit-error ref="chartsRef" v-if="diagram.value.label == '误码率'"></bit-error>
                    <planis-phere ref="chartsRef" v-if="diagram.value.label == '星座图'" :elKey="index"></planis-phere>
                    <wave-form ref="chartsRef" v-if="diagram.value.label == '波形图'"></wave-form>
                    <matrix-diagram ref="chartsRef" v-if="diagram.value.label == '电场E'"></matrix-diagram>
                    <!-- <eye-diagram ref="EyeDiagramRef" v-if="diagram.value.label == '眼图'"></eye-diagram>
                    <bit-error ref="BitErrorRef" v-if="diagram.value.label == '误码率'"></bit-error>
                    <planis-phere ref="PlanisPhereRef" v-if="diagram.value.label == '星座图'"></planis-phere>
                    <wave-form ref="WaveFormRef" v-if="diagram.value.label == '波形图'"></wave-form>
                    <matrix-diagram ref="MatrixDiagramRef" v-if="diagram.value.label == '电场E'"></matrix-diagram> -->
                </div>
            </div>
        </div>
    </div> 
</template>
<script lang="ts">
import { defineComponent} from 'vue';
export default defineComponent({
    name: 'WindowsManager'
})
</script>
<script lang="ts" setup>
import { onMounted, reactive, ref, watch, nextTick, getCurrentInstance} from 'vue';
import { graphManager } from '@/services/phot_client/graph';
import { ipcRenderer } from 'electron'
import { useStore } from "vuex"
import EyeDiagram from './EyeDiagram.vue';
import BitError from './BitError.vue'
import PlanisPhere from './PlanisPhere.vue';
import WaveForm from './WaveForm.vue';
import MatrixDiagram from './MatrixDiagram.vue'
import JSZip from 'jszip'
import jsPDF from 'jspdf';
import FileSaver from 'file-saver'
const { proxy }: any = getCurrentInstance()
const store = useStore()
const windowHeight = ref() as any
const windowWidth = ref() as any
const focusid = ref(0)
const mainWindow = ref()
const diagrams = ref([]) as any
// const EyeDiagramRef = ref();
// const BitErrorRef = ref();
// const PlanisPhereRef = ref();
// const WaveFormRef = ref();
// const MatrixDiagramRef = ref();
const chartsRef = ref();
const windowRef = reactive({
    rightItemList: [
        {
            name: '复制',
            fn:() => {
                copyImg()
            }
        },
    ]
})
let i = 0;
onMounted(()=> {
    document.getElementById('windows')?.addEventListener("DOMSubtreeModified",function(){
        // console.log(document.getElementById('windows')?.clientHeight)
    })
})
const emit = defineEmits({
    'numberChange': (val: any) => {},
    'focusChange': (val: any) => {}
})
watch(diagrams,() => {
    // console.log(diagrams)
    if(diagrams.value.length == 0){
        emit('numberChange',false)
    }else{
        emit('numberChange',true)          
    }
},{
    deep: true
})
const add = async (val:any, opts?: any) => {
    await nextTick()
    // if(!isShow(val)){
        focusid.value = i
        await nextTick()
        let diagramInfo = ref({
            label: val,
            diagramRef: chartsRef,
            state: '1'
        }) as any
        diagrams.value.push(diagramInfo)
        // const refList: any = reactive({
        //     '误码率': BitErrorRef,
        //     '星座图': PlanisPhereRef,
        //     '眼图': EyeDiagramRef,
        //     '波形图': WaveFormRef,
        //     '电场E': MatrixDiagramRef,
        // })
        await nextTick()
        // console.log( opts.index + ':', diagrams.value[opts.index].value.diagramRef[opts.index])
        // if(val == '误码率'){
        //     diagrams.value[i].value.diagramRef = BitErrorRef
        // } else if(val == '星座图'){
        //     diagrams.value[i].value.diagramRef = PlanisPhereRef
        // } else if(val == '眼图'){
        //     diagrams.value[i].value.diagramRef = EyeDiagramRef
        // } else if(val == '波形图'){
        //     diagrams.value[i].value.diagramRef = WaveFormRef
        // } else if(val == '电场E'){
        //     diagrams.value[i].value.diagramRef = MatrixDiagramRef
        // }
        // setTimeout(async () => {
            await diagrams.value[opts.index].value.diagramRef[opts.index].init(opts)
            await judge()
            await reload()
            i += 1;
        // }, 500)
    // }
}
const isShow = (val: any) => {
    let result = false
    for(let i = 0 ; i<diagrams.value.length; i++){
        if(diagrams.value[i].value.label == val){
            result = true
            focusWindow(i)
        }
    }
    return result
}
const deleteWindow = (index:any) =>{
    diagrams.value.splice(index, 1)
    judge()
    reload()
}
const reload = () => {
    for(let i = 0 ; i<diagrams.value.length-1; i++){
        diagrams.value[i].value.diagramRef[0].reload()
    }
}
const copyImg = async () => {
    // console.log(diagrams.value[focusid.value].value)
    const base64Data = await diagrams.value[focusid.value].value.diagramRef[0].getImgUrl();
    const blobInput = dataUrlFile(base64Data,'copy.png');
    const clipboardItemInput = new ClipboardItem({ 'image/png':blobInput});
    navigator.clipboard.write([clipboardItemInput]);
}
const closeAll = () => {
    diagrams.value = []
}
const judge = () => {
    if(diagrams.value.length == 1){
        windowWidth.value = document.getElementById('mainwindow')?.clientWidth
        windowHeight.value = document.getElementById('mainwindow')?.clientHeight
    } else if(diagrams.value.length == 2){
        windowWidth.value = Number(document.getElementById('mainwindow')?.clientWidth) / 2 - 4
        windowHeight.value = document.getElementById('mainwindow')?.clientHeight
    } else{
        windowWidth.value = Number(document.getElementById('mainwindow')?.clientWidth) / 2 - 4
        windowHeight.value = Number(document.getElementById('mainwindow')?.clientHeight) / 2 - 3
    }
}
const savePDF = (val: any) => {
    nextTick(() => {
        diagrams.value[focusid.value].value.diagramRef[0].savePDF()
    })
}
const saveAllPDF = () => {
    nextTick(async () => {
        var doc = new jsPDF('l', 'pt', 'letter')
        // console.log(diagrams.value.length)
        for(let i = 0 ; i<diagrams.value.length; i++){
            let url = await diagrams.value[i].value.diagramRef[0].getImgUrl()
            doc.addImage(url, 100, 5, 590, 590, 'img'+i)
            doc.addPage()
        }
        doc.deletePage(i+1)
        doc.save('test-allPDF')
    })
}
const saveimg = (val: any) => {
    nextTick(() => {
        diagrams.value[focusid.value].value.diagramRef[0].saveimg() 
    })
}
const saveCSV = () => {
    nextTick(() => {
        diagrams.value[focusid.value].value.diagramRef[0].saveCSV()
    })
}
const saveAllCSV = () => {
    nextTick(() => {
        var arr = [] 
        for(let i = 0 ; i<diagrams.value.length; i++){
            arr.push({
                title: diagrams.value[i].value.label+'.csv',
                data: diagrams.value[i].value.diagramRef[0].dataToCSV()
            })
        }
        let zip = new JSZip()
        let fileName = "test-csvfile"
        arr.forEach(item => {
            zip.file(item.title,item.data)
        })
        zip.generateAsync({type: "blob"}).then(content => {
            FileSaver.saveAs(content, fileName); // 利用file-saver保存文件  自定义文件名
        })
    })
}
const saveAllImg = () => {
    nextTick(async () => {
        var arr = [] 
        for(let i = 0 ; i<diagrams.value.length; i++){
            arr.push({
                title: diagrams.value[i].value.label+'.png',
                base64: await diagrams.value[i].value.diagramRef[0].getImgUrl()
            })
        }
        let zip = new JSZip()
        let fileName = "test-file"
        arr.forEach(item => {
            zip.file(item.title,dataUrlFile(item.base64,item.title))
        })
        zip.generateAsync({type: "blob"}).then(content => {
            FileSaver.saveAs(content, fileName); // 利用file-saver保存文件  自定义文件名
        })
    })
}
const dataUrlFile = (url: any, fileName: any) => {
    url = url.toString();
    var arr = url.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], fileName, {type: mime});
}
const focusWindow = (index: any) => {
    focusid.value = index
    if(diagrams.value.length != 0){
        const props = {
            label: diagrams.value[index].value.label,
            state: diagrams.value[index].value.state
        }
        emit('focusChange', props)
    }
}
const changeState = (val: any) => {
    diagrams.value[focusid.value].value.state = val
    if(val == '1'){
        diagrams.value[focusid.value].value.diagramRef[0].changeState('default')
    } else if(val == '2'){
        diagrams.value[focusid.value].value.diagramRef[0].changeState('dark')
    }
}
const init = async (e: any) => {
    // console.log(e)
    if (e.graph) {
        store.state.sysType === 'system'
	    store.dispatch('setSysType', 'system')
	    store.dispatch('setPhotGraph', e.graph)
    }
    if (e.componentOutputs.length > 0) {
        console.log(e.componentOutputs)
        for (let idx = 0; idx < e.componentOutputs.length; idx++) {
            if (e.isAnalyzer) {
                const signals = e.componentOutputs[idx]
                await add('星座图', {data: signals, index: idx, isAnalyzer: true})
            } else {
                let index = 0
                const signals = e.componentOutputs[idx].signals
                for (let i = 0; i < signals.length; i++) {
                    if (i < 2) {
                        await add('星座图', {data: signals[i], index: index})
                        index++
                    }
                }
            }
            // const component = await graphManager.getRenderNode(compo.componentId, e.graphId)
            // console.log(component)
            // if (component.name == 'constellation_diagram') {
            // }
            // if (component.name == 'eye_diagram') {
            //     add('眼图')
            // }
            // if (component.name == 'constellation_diagram') {

            // }
            // if (component.name == 'bits_error_count') {
            //     add('误码率')
            // }
        }
    }
    
}
defineExpose({
    add,
    changeState,
    saveAllImg,
    saveAllCSV,
    saveCSV,
    saveimg,
    savePDF,
    saveAllPDF,
    closeAll,
    init
})
</script>
  
<style lang="scss" scoped>
  #mainwindow{
      width: 100%;
      height: 100%;
      float: left;
      overflow-y:scroll;
  }
  // #windows{
  //     float: left;
  //     width: v-bind(windowWidth);
  //     height: v-bind(windowHeight);
  //     border-style: solid;
  //     border-color: #EBEEF5;
  //     border-width: 0.5px;
  // }
  .focusStyle{
      color: #409EFF;
      z-index: 999;
  }
  // #windowTop{
  //     height: 20px;
  //     display: flex;
  //     flex-direction: row;
  //     background-color: #EBEEF5;
  // }
//   #diagram{
    //   float: left;
    //   padding-left: 2px;
    //   width: 100%;
    //   height: 100%;
//   }
  // #title{
  //     height: 20px;
  //     width: 97%;
  //     font-size:12px;
  //     text-align: center;
  // }
  // #delete{
  //     float: right;
  //     cursor: pointer;
  //     font-size: 15px;
  //     align-items: center;
  //     // padding-right: 0%;
  //     // position: absolute;
  //     // margin-left: 90%;
  //     // margin-top: 100px;
  // }
  </style>